﻿using EasyModbus;
using 工业设备监控系统.Interface;

public class ModbusTcpConnection : IModbusConnection
{
    private ModbusClient _client;
    private readonly string _ip;
    private readonly int _port;

    public bool IsConnected => _client != null && _client.Connected;

    public ModbusTcpConnection(string ip, int port = 502)
    {
        _ip = ip;
        _port = port;
    }

    public bool Connect()
    {
        try
        {
            _client = new ModbusClient(_ip, _port);
            _client.Connect();
            return true;
        }
        catch
        {

            return false;
        }
    }

    public void Disconnect()
    {
        _client?.Disconnect();
    }

    public int[] ReadHoldingRegisters(int startAddress, int count)
    {
        return _client.ReadHoldingRegisters(startAddress, count);
    }

    public void WriteSingleRegister(int address, int value)
    {
        _client.WriteSingleRegister(address, value);
    }

    public void Dispose()
    {
        Disconnect();
    }
}